package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.mapper.*;
import cn.tedu.csmall.product.pojo.entity.SPU;
import cn.tedu.csmall.product.pojo.entity.SpuDetail;
import cn.tedu.csmall.product.pojo.param.SpuAddNewParam;
import cn.tedu.csmall.product.pojo.vo.*;
import cn.tedu.csmall.product.service.ISpuService;
import com.example.csmall.commons.ex.ServiceException;
import com.example.csmall.commons.pojo.vo.PageData;
import com.example.csmall.commons.util.PageInfoToPageDataConverter;
import com.example.csmall.commons.web.ServiceCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * 处理SPU的业务实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */

@Service
@Slf4j
public class SpuServiceImpl implements ISpuService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Override
    public void addNew(SpuAddNewParam spuAddNewParam) {
        log.debug("开始处理【新增SPU】的业务，参数：{}", spuAddNewParam);
        // 检查品牌：是否存在，是否启用
        Long brandId = spuAddNewParam.getBrandId();
        BrandStandardVO brand = brandMapper.getStandardById(brandId);
        if (brand == null) {
            String message = "新增SPU失败，品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (brand.getEnable() == 0) {
            String message = "新增SPU失败，品牌已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查类别：是否存在，是否启用，是否不包含子级
        Long categoryId = spuAddNewParam.getCategoryId();
        CategoryStandardVO category = categoryMapper.getStandardById(categoryId);
        if (category == null) {
            String message = "新增SPU失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (category.getEnable() == 0) {
            String message = "新增SPU失败，类别已经被禁用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        if (category.getIsParent() == 1) {
            String message = "新增SPU失败，选择的类别不允许包含子级类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查相册：是否存在
        Long albumId = spuAddNewParam.getAlbumId();
        AlbumStandardVO album = albumMapper.getStandardById(albumId);
        if (album == null) {
            String message = "新增SPU失败，相册数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 设置SPU的ID

        Long spuId = new Random().nextLong();
        log.debug("spuId的值为：{}", spuId);
        // 创建SPU对象
        SPU spu = new SPU();
        // 赋值属性值
        BeanUtils.copyProperties(spuAddNewParam, spu);
        // 补全属性值：id
        spu.setId(spuId);
        // 补全属性值：brand_name, category_name
        spu.setBrandName(brand.getName());
        spu.setCategoryName(category.getName());
        // 补全：sales, comment_count, positive_comment_count
        spu.setSales(0);
        spu.setCommentCount(0);
        spu.setPositiveCommentCount(0);
        // 补全：is_deleted, is_published, is_new_arrival, is_recommend
        spu.setIsDeleted(0);
        spu.setIsPublished(0);
        spu.setIsNewArrival(0);
        spu.setIsRecommend(0);
        // 补全属性值：is_checked >>> 0, check_user >>> null, gmt_check >>> null
        spu.setIsChecked(0);
        // 插入SPU数据
        int rows = spuMapper.insert(spu);
        if (rows != 1) {
            String message = "新增SPU失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 创建spuDetail对象
        SpuDetail spuDetail = new SpuDetail();
        // 补全属性值：spu_id >>> 与以上Spu的ID相同
        spuDetail.setId(spuId);
        spuDetail.setSpuId(spuId);
        // 补全属性值：detail >>> 来自参数
        spuDetail.setDetail(spuAddNewParam.getDetail());
        // 插入SpuDetail数据
        rows = spuDetailMapper.insert(spuDetail);
        if (rows != 1) {
            String message = "新增SPU失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

    }

    @Override
    public SpuStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询SPU详情】的业务，参数：{}", id);
        SpuStandardVO queryResult = spuMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "根据ID查询SPU详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("即将返回SPU详情：{}", queryResult);
        return queryResult;
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum, pageSize);
    }

    @Override
    public PageData<SpuListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询SPU列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<SpuListItemVO> list = spuMapper.list();
        PageInfo<SpuListItemVO> pageInfo = new PageInfo<>(list);
        PageData<SpuListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }


}
